<template>
	<div class="dashboard-container">
		<div class="app-container">
			<PageTools :show-before="true">
				<span slot="before">共{{page.total}}条记录</span>
				<template slot="after">
					<el-button @click="$router.push('/import')" size="small" type="warning">导入</el-button>
					<el-button @click="exportData" size="small" type="danger">导出</el-button>
					<el-button @click="showDialog = true" size="small" type="primary">新增员工</el-button>
				</template>
			</PageTools>
			<!-- 放置表格和分页 -->
			<el-card v-loading="loading">
				<el-table border stripe :data="list">
					<el-table-column type="index" label="序号" sortable="" />
					<el-table-column prop="username" label="姓名" sortable="" />
					<el-table-column label="头像" align="center">
						<template slot-scope="{row}">
							<img @click="showQrCode(row.staffPhoto)" v-imageerror="require('@/assets/common/head.jpg')"
								:src="row.staffPhoto"
								style="border-radius: 50%; width: 100px; height: 100px; padding: 10px" alt="">
						</template>
					</el-table-column>
					<el-table-column prop="workNumber" label="工号" sortable="" />
					<el-table-column :formatter="formatEmployment" prop="formOfEmployment" label="聘用形式" sortable="" />
					<el-table-column prop="departmentName" label="部门" sortable="" />
					<el-table-column label="入职时间" sortable="">
						<template v-slot="{row}">
							{{ row.timeOfEntry | formatDate }}
						</template>
					</el-table-column>
					<el-table-column label="账户状态" sortable="">
						<template v-slot="{row}">
							<el-switch :value="row.enableState === 1"></el-switch>
						</template>
					</el-table-column>
					<el-table-column label="操作" sortable="" fixed="right" width="280">
						<template v-slot="{row}">
							<el-button @click="$router.push(`/employees/detail/${row.id}`)" type="text" size="small">查看
							</el-button>
							<el-button type="text" size="small">转正</el-button>
							<el-button type="text" size="small">调岗</el-button>
							<el-button type="text" size="small">离职</el-button>
							<el-button @click="editRole(row.id)" type="text" size="small">角色</el-button>
							<el-button @click="deleteEmployee(row.id)" type="text" size="small">删除</el-button>
						</template>
					</el-table-column>
				</el-table>
				<!-- 分页组件 -->
				<el-row type="flex" justify="center" align="middle" style="height: 60px">
					<el-pagination :current-page="page.page" :page-size="page.pagesize" :total="page.total"
						@current-change="changePage" layout="prev, pager, next" />
				</el-row>
			</el-card>

			<el-dialog title="二维码" :visible.sync="showCodeDialog">
				<el-row type="flex" justify="center">
					<canvas ref="myCanvas"></canvas>
				</el-row>
			</el-dialog>

			<AddEmployee :showDialog.sync="showDialog" />
			<AssignRole ref="assignRole" :showRoleDialog.sync="showRoleDialog" :userId="userId"></AssignRole>
		</div>
	</div>
</template>


<script>
	import QrCode from 'qrcode'

	import {
		getEmployeeList,
		delEmployee
	} from '@/api/employees'

	import AddEmployee from './components/add-employee.vue'
	import AssignRole from './components/assign-role.vue'
	import EmployeeEnum from '@/api/constant/employees'
	import {
		formatDate
	} from '@/filters/index.js'

	export default {
		components: {
			AddEmployee,
			AssignRole
		},

		data() {
			return {
				loading: false,
				list: [],
				page: {
					page: 1,
					size: 10,
					total: 0
				},
				showDialog: false,
				showCodeDialog: false,
				showRoleDialog: false,
				userId: ''
			}
		},

		created() {
			this.getEmployeeList()
		},

		methods: {
			changePage(newPage) {
				this.page.page = newPage
				this.getEmployeeList()
			},

			async getEmployeeList() {
				this.loading = true
				try {
					const {
						total,
						rows
					} = await getEmployeeList(this.page)
					this.page.total = total
					this.list = rows
				} catch (e) {
					this.$message.error(e)
				}
				this.loading = false
			},

			formatEmployment(row, column, cellValue, index) {
				const obj = EmployeeEnum.hireType.find(item => item.id === cellValue)
				return obj ? obj.value : '未知'
			},

			async deleteEmployee(id) {
				try {
					await this.$confirm('您确定删除该员工吗')
					await delEmployee(id)
					this.getEmployeeList()
					this.$message.success('删除员工成功 ')
				} catch (e) {
					this.$message.error(e)
				}
			},

			exportData() {
				const headers = {
					'姓名': 'username',
					'手机': 'mobile',
					'入职日期': 'timeOfEntry',
					'聘用形式': 'formOfEmployment',
					'转正日期': 'correctionTime',
					'工号': 'workNumber',
					'部门': 'departmentName'
				}

				import('@/vendor/Export2Excel').then(async excel => {
					const {
						rows
					} = await getEmployeeList({
						page: 1,
						size: this.page.total
					})
					const data = this.formatJson(headers, rows)
					excel.export_json_to_excel({
						header: Object.keys(headers),
						data, //具体数据 必填
						filename: 'ihrm人力资源用户表', //非必填
						autoWidth: true, //非必填
						bookType: 'xlsx' //非必填
					})
				})
			},

			formatJson(headers, rows) {
				return rows.map(item => {
					return Object.values(headers).map(value => {
						if (value === 'formOfEmployment') {
							const obj = EmployeeEnum.hireType.find(o => (o.id + '') === (item[value] +
								''))
							return obj ? obj.value : '未知'
						} else if (value === 'timeOfEntry' || value === 'correctionTime') {
							return formatDate(item[value])
						}
						return item[value]
					})
				})
			},

			showQrCode(url) {
				// url存在的情况下 才弹出层
				if (url) {
					this.showCodeDialog = true // 数据更新了 但是我的弹层会立刻出现吗 ？页面的渲染是异步的！！！！
					// 有一个方法可以在上一次数据更新完毕，页面渲染完毕之后
					this.$nextTick(() => {
						// 此时可以确认已经有ref对象了
						QrCode.toCanvas(this.$refs.myCanvas, url) // 将地址转化成二维码
					})
				} else {
					this.$message.warning('该用户还未上传头像')
				}
			},

			async editRole(id) {
				this.userId = id // props传值 是异步的
				await this.$refs.assignRole.getUserDetailById(id) // 父组件调用子组件方法
				this.showRoleDialog = true
			},
		},
	}
</script>

<style scoped>

</style>
